package com.foogui.bootjdbctemplate.callback;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 采用回调接口的方式代替了模板方式,就可以采用函数式编程
 *
 * @author Foogui
 * @date 2023/04/12
 */
@Repository
public class CallbackJdbcTemplate  {

    /**
     * 遗留问题：数据源Bean无法注入
     */
    private DataSource dataSource;
    @Autowired
    public CallbackJdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
        System.out.println("6666");
        System.out.println(dataSource);
    }

    public final Object executeQuery(String sql,StatementCallback callback) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            Object object = callback.handleResultSet(resultSet);
            return object;
        } catch (SQLException e) {
            System.out.print(e);
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                }
            }
        }
        return null;
    }

}